package com.cat.math;

import java.util.ArrayList;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/closest-prime-numbers-in-range/description/
 * @create 2025/10/16 15:47
 * @since JDK17
 */

public class Solution10 {
    static int N = ((int) (1e6 + 10));
    static boolean[] isPrime = new boolean[N];
    static ArrayList<Integer> list = new ArrayList<>();

    static {
        isPrime[0] = isPrime[1] = true;
        for (int i = 2; i < N; i++) {
            if (!isPrime[i]) {
                list.add(i);
                for (long j = (long) i * i; j < N; j += i) {
                    isPrime[((int) j)] = true;
                }
            }
        }
    }

    public int[] closestPrimes(int left, int right) {
        int diff = Integer.MAX_VALUE;
        int[] ans = new int[]{-1, -1};
        for (int i = 1; i < list.size(); i++) {
            int cur = list.get(i), last = list.get(i - 1);
            if (cur > right) {
                break;
            }
            if (last >= left && cur - last < diff) {
                diff = cur - last;
                ans = new int[]{last, cur};
            }
        }
        return ans;
    }
}
